﻿
var cellPrefix = 'JEPrepCell_';
var processing;

var gauge;


$(document).ready(function () {
    polyfillStartsWith();
    HideHeaderData();
    //registerJEPrepButtons();
    registerJEPrepGridButtons($(document));
    registerCCYFields($(document));
    //registerJEPrepDateFields();
    registerJEPrepValidationFields();  //Generated with page
    registerJEPrepResizeColumns();  //Generated with page
    JEPrepSetLastCellClass();
    CheckStartupMessages();
    //DisableControlsAsNeeded();
    updateDrCrTotals();
    DisableHeaderAndDetailAsNeeded();
    initGridInputWidth();
    InitializeAutocomplete();
    fixjQueryDateValidation();
    updateDynConversionAmount();
    $('#DocumentAmountPrevious').click(PreviousCCY);
    $('#DocumentAmountHome').click(HomeCCY);
    $('#DocumentAmountNext').click(NextCCY);
    $('#ConvPrevious').click(PreviousConv);
    $('#ConvNext').click(NextConv);
    var CCYCode = ".JEPrep" + $("#CCYBucket").val() + "Code";
    $(CCYCode).blur(updateDynConversionAmount);
    processing = false;
    $('#Period').change(function (e) {
        RefreshReversalPeriodList(e);
    });
    $('#ReversalPeriod').change(function (e) {
        ResetValidationForReversalPeriod(e);
    });
    setupConfirmReopenDialog();

    setRiskRating();
})

$(window).load(function () {
    setReverseValidation();
    registerPageLoadEvents();
});

function registerPageLoadEvents() {
    setReversalPeriod();
    registerJEGridEvents();
}

function polyfillStartsWith() {
    if (!String.prototype.startsWith) {
        String.prototype.startsWith = function (search, pos) {
            return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
        };
    }
}

// returning true so only doing server side validation of date
function fixjQueryDateValidation() {
    jQuery.validator.addMethod('date',
        function (value, element) {
            return true;
        });
}

function setReverseValidation() {
    $('#ReverseJEDialog form').validate({ errorClass: "jeprep-validation-error" });
    $('#ReversePostingDate').rules("add", {
        required: true
    });

    $('#ReversePeriodSelectList').rules("add", {
        required: true
    });
}

function CheckStartupMessages() {

    var hasStartupPopup = $('#HasStartupPopup').val();
    var hasStartupMessage = $('#HasStartupMessage').val();
    var startupMessageText = $('#StartupMessageText').val();

    if (hasStartupMessage == 'True') {
        $('#JEPrepPageMsg').show();
        $('#JEPrepPageMsg').html(startupMessageText);
        //not returning yet because you could have both a popup and an informational message perhaps
    }

    if (hasStartupPopup == 'True') {
        OpenMessageDialog(startupMessageText);
        return;
    }
}

function registerJEPrepButtons() {
   // $('#RevisionSelectList').change(function(e) { return GetSelectedRevision(); });
}

function registerCCYFields(parentObj) {
    $(parentObj).find('.JEPrepCCY1').blur(function (event) { CCYFieldChanged($(event.target).parents('.JEPrepRow')); updateDrCrTotals(); updateDynConversionAmount(); });
    $(parentObj).find('.JEPrepCCY2').blur(function (event) { CCYFieldChanged($(event.target).parents('.JEPrepRow')); updateDrCrTotals(); updateDynConversionAmount(); });
    $(parentObj).find('.JEPrepCCY3').blur(function (event) { CCYFieldChanged($(event.target).parents('.JEPrepRow')); updateDrCrTotals(); updateDynConversionAmount(); });
}

function CCYFieldChanged(row) {
    var rowObj = $(row);
    var ccy1 = rowObj.find('.JEPrepCCY1').val();
    var ccy2 = rowObj.find('.JEPrepCCY2').val();
    var ccy3 = rowObj.find('.JEPrepCCY3').val();

    if (GetDecimalSeparator() != '.') {
        ccy1 = SwapDecimalCharacters(ccy1);
        ccy2 = SwapDecimalCharacters(ccy2);
        ccy3 = SwapDecimalCharacters(ccy3);
    }

    var ccy1Num = Number(ccy1);
    var ccy2Num = Number(ccy2);
    var ccy3Num = Number(ccy3);

    if (ccy1Num < 0 || ccy2Num < 0 || ccy3Num < 0) {
        rowObj.addClass('JEPrepCreditRow');
        rowObj.removeClass('JEPrepDebitRow');
    }
    else {
        rowObj.removeClass('JEPrepCreditRow');
        rowObj.addClass('JEPrepDebitRow');
    }
}

$.fn.digits = function () {
    var decimalSeparator = GetDecimalSeparator();
    var thousandthSeparator = decimalSeparator == "." ? "," : ".";
    var results = $(this).text().split(decimalSeparator);
    var result = results[0];
    var mantissa = results[1];
    return this.each(function () {
        $(this).text((result.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1" + thousandthSeparator ) + decimalSeparator + mantissa));
    })
}

function SaveCurrentConvType(JEId, type) {
    $.cookie.raw = true;
    var cookieName = 'JESelectedDynConvType_' + JEId;
    $.cookie(cookieName, type, { path: '/', expires: 2 });
}

function SaveCurrentConvCode(JEId, code) {
    $.cookie.raw = true;
    var cookieName = 'JESelectedDynConvCode_' + JEId;
    $.cookie(cookieName, code, { path: '/', expires: 2 });
}

function CurrentConvType() {
    var JEId = $("#JEGuid").val();
    var currConvType = GetCurrentConvType(JEId);
    if (!currConvType) {
        currConvType = myConvs[0].rateType;
        SaveCurrentConvType(JEId, currConvType);
    }
    return currConvType;
}

function CurrentConvCode() {
    var JEId = $("#JEGuid").val();
    var currConvCode = GetCurrentConvCode(JEId);
    if (!currConvCode) {
        currConvCode = myConvs[0].rateCode;
        SaveCurrentConvCode(JEId, currConvCode);
    }
    return currConvCode;
}

function GetCurrentConvType(JEId) {
    $.cookie.raw = true;
    var cookieName = 'JESelectedDynConvType_' + JEId;
    return $.cookie(cookieName);
}

function GetCurrentConvCode(JEId) {
    $.cookie.raw = true;
    var cookieName = 'JESelectedDynConvCode_' + JEId;
    return $.cookie(cookieName);
}

function NextConv() {
    var JEId = $("#JEGuid").val();
    var nextIdx = currConvIdx + 1;
    if (nextIdx >= myConvs.length) {
        nextIdx = 0;
    }

    SaveCurrentConvType(JEId, myConvs[nextIdx].rateType);
    SaveCurrentConvCode(JEId, myConvs[nextIdx].rateCode);
    updateDynConversionAmount();
}

function PreviousConv() {
    var JEId = $("#JEGuid").val();
    var prevIdx = currConvIdx - 1;
    if (prevIdx < 0) {
        prevIdx = myConvs.length - 1;
    }

    SaveCurrentConvType(JEId, myConvs[prevIdx].rateType);
    SaveCurrentConvCode(JEId, myConvs[prevIdx].rateCode);
    updateDynConversionAmount();
}

function updateDynConversionAmount() {
    var convAmt = 0;
    var swapDecimal = GetDecimalSeparator() != '.';
    var ccy1DebitTotal = 0;
    var ccy1CreditTotal = 0;
    var ccy1Diff = 0;
    var CCYCode = ".JEPrep" + $("#CCYBucket").val() + "Code";
    var rateFromCode = $(CCYCode).val();

    if ($('#ConvertedAmount').length > 0) {
        if ($(CCYCode).length == 0) {
            $('#ConvertedAmount').html($('#App_ERROR_Allcaps').val());
            return;
        }

        var currCode = CurrentConvCode();
        var currType = CurrentConvType();

        // Need to find the labels for Document Amounts
        // currCCYIdx is global for the next and previous buttons
        var currLabels;
        $.each(myConvs, function (idx, elem) {
            if (elem.rateType == currType &&
                    elem.rateCode == currCode) {
                currConvIdx = idx;
                currLabels = elem;
                return false;
            }
        });

        // If no label is defined then set the first one, this is if they update a Range of value Table
        if (!currLabels) {
            currLabels = myConvs[0];
            SaveCurrentConvCode(JEId, currLabels.rateCode);
            SaveCurrentConvType(JEId, currLabels.rateType);
        }

        // String.format("this {0}", "test")
        $('#RateTypeLabel').html(String.format(currLabels.rateTypeLabel, rateFromCode));
        $('#RateType').html($('#JournalEntry_RateNotDefined').val());
        $('#ConvertedLabel').html(currLabels.rateCodeLabel);
        $('#ConvertedAmount').html($('#JournalEntry_RateNotDefined').val());

        if ($('#PeriodEffDate').val().length <= 0) {
            $('#RateType').html($('#EffDateRequired').val());
            $('#ConvertedAmount').html($('#EffDateRequired').val());
            return;
        }

        CreateBatches = $('#SecCreateBatches').val();

        if (CreateBatches != null && (CreateBatches == true || CreateBatches.toString().toLowerCase() == 'true')) {
            var ccy1 = 0;
            ccy1 = $('#SecCreditTotal').val();
            if (swapDecimal) {
                ccy1 = SwapDecimalCharacters(ccy1);
            }
            var ccy1Num = Number(ccy1);

            ccy1CreditTotal = ccy1CreditTotal + ccy1Num;

            ccy1 = 0;
            ccy1 = $('#SecDebitTotal').val(); ;
            if (swapDecimal) {
                ccy1 = SwapDecimalCharacters(ccy1);
            }
            ccy1Num = Number(ccy1);
            ccy1DebitTotal = ccy1DebitTotal + ccy1Num;

            ccy1Diff = Math.round((ccy1CreditTotal + ccy1DebitTotal) * 100000) / 100000;  //Fixes JS floating point math rounding issues.
        }
        else {
            var jePrep = '.JEPrep' + $("#CCYBucket").val();
            $('.JEPrepRow').not('.JEPrepRowTemplate').find(jePrep).each(function (i, eachCCY) {
                var ccy1 = $(eachCCY).val();
                if (swapDecimal) {
                    ccy1 = SwapDecimalCharacters(ccy1);
                }
                var ccy1Num = Number(ccy1);
                if (ccy1Num < 0) {
                    ccy1CreditTotal = ccy1CreditTotal + ccy1Num;
                    //ccy1CreditTotal = ccy1CreditTotal + (ccy1Num * -1);
                }
                else {
                    ccy1DebitTotal = ccy1DebitTotal + ccy1Num;
                }
                ccy1Diff = Math.round((ccy1CreditTotal + ccy1DebitTotal) * 100000) / 100000;  //Fixes JS floating point math rounding issues.
            });
        }

        if ($('#DynamicRoutingAmount').val() == "TotalCredits") {
            convAmt = ccy1CreditTotal;
        }
        else {
            convAmt = ccy1DebitTotal;
        }

        $('#ConvertedAmount').html($('#App_Loading_ALLCAPS_Ellipses').val());
        // rateObj is defined in _JEPrep.cshtml
        var rate = rateObj[currType.toUpperCase() + ':' + rateFromCode.toUpperCase() + ':' + currCode.toUpperCase()];

        if (typeof rate != 'undefined') {
            var floatRate = parseFloat(rate);
            if (!isNaN(floatRate)) {
                var rateDisplay = floatRate.toFixed(5);
                rateDisplay = SwapDecimalCharacters(rateDisplay);
                $('#RateType').html(rateDisplay);

                convAmt = convAmt * rate;
                //var convAmtDisplay = convAmt.toFixed(5).replace(/0{0,3}$/, "");
                var convAmtDisplay = convAmt.toFixed(2);
                if (swapDecimal) {
                    convAmtDisplay = convAmtDisplay.replace(".", ",");
                }

                $('#ConvertedAmount').html(convAmtDisplay);
                $('#ConvertedAmount').digits();
                return;
            }
            else {
                $('#ConvertedAmount').html($('#JournalEntry_RateNotDefined').val());
            }
        }
        else {
            $('#ConvertedAmount').html($('#JournalEntry_RateNotDefined').val());
        }
    }
}

function SaveCurrentCCY(JEId, CCY) {
    $.cookie.raw = true;
    var cookieName = 'JESelectedCCY_' + JEId;
    $.cookie(cookieName, CCY, { path: '/', expires: 2 });
}

function GetCurrentCCY(JEId) {
    $.cookie.raw = true;
    var cookieName = 'JESelectedCCY_' + JEId;
    return $.cookie(cookieName);
}

function NextCCY() {
    var JEId = $("#JEGuid").val();
    var nextIdx = currCCYIdx + 1;
    if (nextIdx >= myDocAmounts.length) {
        nextIdx = 0;
    }

    SaveCurrentCCY(JEId, myDocAmounts[nextIdx].suffix);
    updateDrCrTotals();
}

function CurrentCCYString() {
    var JEId = $("#JEGuid").val();
    var currCCY = GetCurrentCCY(JEId);
    if (! currCCY) {
        currCCY = $("#CCYBucket").val();
        SaveCurrentCCY(JEId, currCCY);
   }
    return currCCY;
}

function HomeCCY() {
    var JEId = $("#JEGuid").val();
    var currCCY = $("#CCYBucket").val();
    $.each(myDocAmounts, function (idx, elem) {
        if (elem.suffix == currCCY) {
            currCCYIdx = idx;
            return false;
        }
    });

    SaveCurrentCCY(JEId, myDocAmounts[currCCYIdx].suffix);
    updateDrCrTotals();
}

function PreviousCCY() {
    var JEId = $("#JEGuid").val();
    var prevIdx = currCCYIdx - 1;
    if (prevIdx < 0) {
        prevIdx = myDocAmounts.length - 1;
    }

    SaveCurrentCCY(JEId, myDocAmounts[prevIdx].suffix);
    updateDrCrTotals();
}

function updateDrCrTotals() {
    var ccy1DebitTotal = 0;
    var ccy1CreditTotal = 0;
    var ccy1Diff = 0;
    var swapDecimal = GetDecimalSeparator() != '.';
    var CreateBatches = false;
    var currCCY = CurrentCCYString();
    // Need to find the labels for Document Amounts
    // currCCYIdx is global for the next and previous buttons
    var currLabels;
    $.each(myDocAmounts, function (idx, elem) {
        if (elem.suffix == currCCY) {
            currCCYIdx = idx;
            currLabels = elem;
            return false;
        }
    });

    if (!currLabels) {
        if (myDocAmounts.length > 0) {
            var JEId = $("#JEGuid").val();
            currLabels = myDocAmounts[0];
            SaveCurrentCCY(JEId, currLabels.suffix);
        }
        else {
            SaveCurrentCCY(JEId, "");
            return;
        }
    }
    
    CreateBatches = $('#SecCreateBatches').val();

    if (CreateBatches != null && (CreateBatches == true || CreateBatches.toString().toLowerCase() == 'true')) {
        var ccy1 = 0;
        ccy1 = $('#SecCreditTotal').val();
        if (swapDecimal) {
            ccy1 = SwapDecimalCharacters(ccy1);
        }
        var ccy1Num = Number(ccy1);

        ccy1CreditTotal = ccy1CreditTotal + ccy1Num;

        ccy1 = 0;
        ccy1 = $('#SecDebitTotal').val(); ;
        if (swapDecimal) {
            ccy1 = SwapDecimalCharacters(ccy1);
        }
        ccy1Num = Number(ccy1);
        ccy1DebitTotal = ccy1DebitTotal + ccy1Num;

        ccy1Diff = Math.round((ccy1CreditTotal + ccy1DebitTotal) * 100000) / 100000;  //Fixes JS floating point math rounding issues.
    }
    else {
        var jePrep = '.JEPrep' + currCCY;
        $('.JEPrepRow').not('.JEPrepRowTemplate').find(jePrep).each(function (i, eachCCY) {
            var ccy1 = $(eachCCY).val();
            if (swapDecimal) {
                ccy1 = SwapDecimalCharacters(ccy1);
            }
            var ccy1Num = Number(ccy1);
            if (ccy1Num < 0) {
                ccy1CreditTotal = ccy1CreditTotal + ccy1Num;
                //ccy1CreditTotal = ccy1CreditTotal + (ccy1Num * -1);
            }
            else {
                ccy1DebitTotal = ccy1DebitTotal + ccy1Num;
            }
            ccy1Diff = Math.round((ccy1CreditTotal + ccy1DebitTotal) * 100000) / 100000;  //Fixes JS floating point math rounding issues.
        });
    }
    var ccy1DebitDisplay = '';
    var ccy1CreditDisplay = '';
    var ccy1DiffDisplay = '';
    if (!isNaN(ccy1DebitTotal) && !isNaN(ccy1CreditTotal) && !isNaN(ccy1Diff)) {
        ccy1DebitDisplay = ccy1DebitTotal.toFixed(5).replace(/0{0,3}$/, "");
        ccy1CreditDisplay = ccy1CreditTotal.toFixed(5).replace(/0{0,3}$/, "");
        ccy1DiffDisplay = ccy1Diff.toFixed(5).replace(/0{0,3}$/, "");
        if (swapDecimal) {
            ccy1DebitDisplay = ccy1DebitDisplay.replace(".", ",");
            ccy1CreditDisplay = ccy1CreditDisplay.replace(".", ",");
            ccy1DiffDisplay = ccy1DiffDisplay.replace(".", ",");
        }
    }
    $('#CCY1DebitTotal').html(ccy1DebitDisplay);
    $('#CCY1DebitTotal').digits();
    $('#CCY1CreditTotal').html(ccy1CreditDisplay);
    $('#CCY1CreditTotal').digits();
    $('#CCY1Diff').html(ccy1DiffDisplay);
    $('#CCY1Diff').digits();

    $('#TotalDebitLabel').html(currLabels.debitLabel);
    $('#TotalCreditLabel').html(currLabels.creditLabel);
    $('#TotalDiffLabel').html(currLabels.diffLabel);
}

function SwapDecimalCharacters(stringValue) {
    if (stringValue == null) return null;
    return stringValue.replace(",", ".");
}

var fileDownloadCheckTimer;

function onMenuSelect(e) {
    if (processing)
        return;

    $('#ImportStatusPanelBar').hide();
    $("#journalStatus").show();
    $("#journalErrorMessage").html("");
    var id = $(e.item).attr('id')
    if (id == 'JEPrepClearGrid'){
        JEPrepClearGridClicked();
        return;
    }
    if (id ==  'JEPrepAttachFilesButton'){
        FilesClicked(e);
        return;
    }
    if (id == 'JEPrepImportButton') {
        ImportClicked();
        return;
    }
    if (id == 'JEPrepApproverRoutingButton') {
        JEActionWithWholeForm("savethenapproutingpopup");
        //JEPrepApproverRoutingClicked();
        return;
    }
    if (id == 'JEPrepPreparerRoutingButton') {
        JEActionWithWholeForm('savethenpreproutingpopup');
        return;
    }
    if (id == 'JEPrepSaveButton') {
        JEActionWithWholeForm("save");
        return;
    }
    if (id == 'JEPrepSubmitButton') {
        JEActionWithWholeForm("submitpreprocessing");
        //JEActionWithEmailForm("submit");
        return;
    }
    if (id == 'JEPrepNextPreparerButton') {
        JEActionWithWholeForm('submitNextPreparer');
        return;
    }
    if (id == 'JEPrepValidateButton') {
        JEActionWithWholeForm("validate");
        return;
    }
    if (id == 'JEPrepReverseCCYButton') {
        JEActionWithWholeForm("reverseccy");
        return;
    }
    if(id == 'JEPrepSaveDraftScheduleTemplateButton') {
        JEActionWithWholeForm("savedraftfortemplate");
        return;
    }
    if (id == 'JEPrepValidateScheduleTemplateButton') {
        JEActionWithWholeForm("validatefortemplate");
        return;
    }
    
    if (id == 'JEPrepApproveButton') {
        var warnings = $('#jeApproverWarnings').html();
        if (warnings.length > 0) {
            var warningLabel = $('#warningLabel').text();
            var okLabel = $('#okLabel').text();
            var continueLabel = $('#continueLabel').text();
            $('.confirmDialog .ui-button-text:contains(' + okLabel + ')').text(continueLabel);
            JEPrepOpenConfirmDialog(warningLabel,
                    warnings,
                    function () { JEActionWithEmailForm("approve"); });
            return;
        }
        else {
            JEActionWithEmailForm("approve");
            return;
        }
    }
    if (id == 'JEPrepRejectButton') {
        JEActionWithEmailForm("reject");
        return;
    }
    if (id == 'JEPrepDeleteButton') {
        JEDeleteAction();
        return;
    }
    if (id == 'JEPrepCreateNotes') {
        GetJENotesContent(event);
        return;
    }
    if (id == 'JEPrepAuditTrailButton') {
        JEPrepAuditTrailClicked();
        return;
    }
    if (id == 'JEPrepReverseButton') {
        JEPrepReverseButtonClicked();
        return;
    }
    if (id == 'JEPrepExportToExcelButton') {
        BodyBusy();
        DisableButtons();
        fileDownloadCheckTimer = window.setInterval(function () {
            CheckExportToExcelComplete();
        }, 1000);
        //JEDetailExportToExcel();
       
        return;
    }
    if (id == 'JEPrepReProcessReversalButton') {
        JEPrepReprocessReversalButtonClicked();
        return;
    }
    if (id == 'JEPrepUnlockJEForPostingButton') {
        JEPrepUnlockJEForPostingButtonClicked();
        return;
    }
    if (id == 'JEPrepReopenButton') {
        JEPrepReopenButtonClicked();
        return;
    }
}

function finishDownload() {
    EnableButtons();
    BodyDefault();
    window.clearInterval(fileDownloadCheckTimer);
}

function registerJEPrepGridButtons(parentObj) {
    var enableDetailGrid = $('#SecEnableDetailGrid').val();
    if (enableDetailGrid == "True") {
        parentObj.find('.JEPrepAddRow').click(function (event) { JEPrepAddRemoveRowClicked(event, 'add'); });
        parentObj.find('.JEPrepDeleteRow').click(function (event) { JEPrepAddRemoveRowClicked(event, 'remove') });
    }
}

function registerJEPrepDateFields() {
    $('.JEPrepDate').datepicker();
}

//Register Submit dialog 2-way for posting decision
$(function () {
    var labelPostNow = $('#labelPostNow').text();
    var labelCancel = $('#cancelLabel').text();
    var buttonsArray = {};
    buttonsArray[labelPostNow] = function () { $(this).dialog('close'); JESubmitPostingDecisionFromUI('postnow'); };
    buttonsArray[labelCancel] = function () { $(this).dialog('close'); JESubmitPostingDecisionFromUI('postcancel'); };

    $('#JEPrep_Submit_Post_Dialog_2way').dialog(
        { autoOpen: false,
            modal: true,
            resizable: false,
            zIndex: 10000,
            draggable: true,
            buttons: buttonsArray
        })
});

//Register Submit dialog 3-way for posting decision
$(function () {
    var labelPostNow = $('#labelPostNow').text();
    var labelPostAfterLastRole = $('#labelPostAfterLastApprover').text();
    var labelCancel = $('#cancelLabel').text();
    var buttonsArray = {};
    buttonsArray[labelPostNow]           = function () { $(this).dialog('close'); JESubmitPostingDecisionFromUI('postnow'); };
    buttonsArray[labelPostAfterLastRole] = function () { $(this).dialog('close'); JESubmitPostingDecisionFromUI('postlater'); };
    buttonsArray[labelCancel] = function () { $(this).dialog('close'); JESubmitPostingDecisionFromUI('postcancel'); };

    $('#JEPrep_Submit_Post_Dialog_3way').dialog(
        {   autoOpen: false,
            modal: true,
            resizable: false,
            zIndex: 10000,
            draggable: true,
            buttons: buttonsArray
        })
});


//Register confirm dialog
$(function () {
    var cancelLabel = $('#cancelLabel').text();
    var okLabel = $('#okLabel').text();
    var buttonsArray = {};
    buttonsArray[okLabel] = function () { $(this).dialog('close'); $(this).data('successFunction').call() };
    buttonsArray[cancelLabel] = function () { $(this).dialog('close'); };

    $('#JEPrep_Confirm_Dialog').dialog(
        { autoOpen: false,
            modal: true,
            resizable: false,
            buttons: buttonsArray,
            dialogClass: 'confirmDialog'
        })
    });

//Register notes dialog
$(function () {
    var createLabel = $('#okLabel').text();
    var closeLabel = $('#closeLabel').text();
    var notesTitle = $('#jeNotes').text();
    var buttonsArray = {};
    buttonsArray[closeLabel] = function () { CloseNotesDialog(); };

    $('#NotesDialog').dialog(
    {
        autoOpen: false,
        modal: true,
        resizable: false,
        title: notesTitle,
        zIndex: 10000,
        width: 800,
        height: 600,
        draggable: true,
        position: 'bottom',
        buttons: buttonsArray,
        close: function(event, ui) {
            extendValidatorMessagesForMainPage();
        }
    });
});

//Register file attachment dialog
$(function () {
    var closeLabel = $('#closeLabel').text();
    var buttonsArray = {};
    buttonsArray[closeLabel] = function () { CloseFileAttachmentsDialog(); };

    $('#FileAttachments').dialog({
        autoOpen: false,
        height: 500,
        width: 900,
        modal: true,
        title: FileAttachmentsTitle(),
        zIndex: 10000,
        resizable: false,
        buttons: buttonsArray
    });
});


function CheckExportToExcelComplete() {
    $.ajax({
        type: "get",
        url: GetExportToExcelSessionURL(),
        success: GetExportToExcelSessionValue,
        error: DisplayTrintechAjaxError,
        cache: false
    });
}

function GetExportToExcelSessionValue(packet) {
    if (packet.IsExportExcelComplete) {
        finishDownload();
    }
}

function FilesClicked(event) {
    var jeId = $('#Id').val();
    var packet = { jeId: jeId };
    $.ajax({
        type: "get",
        data: packet,
        url: DisplayFileAttachmentsURL(),
        success: OpenFileAttachmentsDialog,
        error: DisplayTrintechAjaxError,
        cache: false
    });
}

function UploadNewFileComplete(result) {
    if (result.isError) {
        OpenExceptionDialog(result.errorMessage);
}
    else {
        var jeId = $('#Id').val();
        var packet = { jeId: jeId };
        $.ajax({
            type: "get",
            data: packet,
            url: DisplayFileAttachmentsURL(),
            success: SetFileAttachmentsContent,
            error: DisplayTrintechAjaxError,
            cache: false
        });
    }
}

function SetFilesButtonLabel() {
    var fileCount = $('#fileInfoList tr').length;
    // need to subtract the row that is the table heading.
    if (fileCount > 0) {
        fileCount--;
    }
    var fileLabelText = FileAttachmentsTitle() + '(' + (fileCount.toString()) + ')';
    $('#JEPrepAttachFilesButton span').contents(':last').replaceWith(fileLabelText);
}


function SetFileAttachmentsContent(packet) {
   $('#FileAttachments').html(packet);
   SetFilesButtonLabel();
}

function OpenFileAttachmentsDialog(packet) {
    SetFileAttachmentsContent(packet);
    $('#FileAttachments').dialog('open');
}

function CloseFileAttachmentsDialog() {
    $('#FileAttachments').dialog('close');
}

function CancelNewFile() {
    $('#divNewFileDetails').hide();
}

//register reverse form
$(function () {
    var createLabel = $('#okLabel').text();
    var cancelLabel = $('#cancelLabel').text();
    var buttonsArray = {};
    buttonsArray[createLabel] = function () { ReverseSelected(); }
    buttonsArray[cancelLabel] = function () { CloseReverseDialog(); };

    $('#ReverseJEDialog').dialog(
    { autoOpen: false,
        modal: true,
        resizable: false,
        width: 400,
        buttons: buttonsArray
    })
});


//Register Routing Dialog
$(function () {
    //var createLabel = JEDashboardGetOKLabel();
    //var cancelLabel = $('#cancelLabel').text();
    //var buttonsArray = {};
    //buttonsArray[createLabel] = function () { CreateJE(); }
    //buttonsArray[cancelLabel] = function () { CloseRoutingDialogFromButtonArray(); };
    //then below you would put    buttons: buttonsArray

    $('#RoutingDialog').dialog(
    { autoOpen: false,
        modal: true,
        resizable: false,
        height: 'auto',
        width: 'auto',
        zIndex: 10000,
        draggable: true,
        close: function (event, ui) {
            RoutingDialogClose();
        }
    })
});

//Register Audit Trail Dialog
$(function () {
    var closeLabel = $('#closeLabel').text();
    var buttonsArray = {};
    buttonsArray[closeLabel] = function () { CloseAuditTrailDialog(); };

    $('#JEAuditTrailDialog').dialog(
    { autoOpen: false,
        modal: true,
        resizable: false,
        height: 550,
        width: 950,
        zIndex: 10000,
        draggable: true,
        buttons: buttonsArray
    })
});


/**** GENERAL UTILITIES ==================================================================================== ****/

function resetPageMessage() {
    $('#JEPrepPageMsg').hide();
    $('#JEPrepPageMsg').html('');
}

function JEResetValidationErrors() {
    $('.JEValidatable').removeClass("input-validation-error");
    //Remove error labels.  Cannot use jquery validate resetForm because this will clear the values of the cells.
    $('label.jeprep-validation-error').remove();
    $('.jeprep-validation-error').removeClass('jeprep-validation-error');
}

function ResetReverseJEErrors() {
    $('span.field-validation-error span').remove();
    $('.input-validation-error')
    .removeClass('input-validation-error')
    .addClass('valid');
}

function JEHighlightFieldErrors(errorDictionary) {
    try {
        $('#JEPrepForm').validate().showErrors(errorDictionary);
    } catch (err)
    {
        // ignore showErrors errors in case of dynamically adding rows which HTML is not generated and it fails to find row id in DOM
    }
}

function JERefreshPrepPage() {
    var jeId = $('#Id').val();
    var packet = {jeId: jeId};

    $.ajax({
        type: "get",
        url: JERefreshPageURL(),
        data: packet,
        success: JERefreshPrepPageSuccess,
        error: DisplayTrintechAjaxError,
        cache: false
    });
}
function JERefreshPrepPageSuccess(packet) {
    // ensures that only html strings are attempted to be rendered; sometimes an object is passed
    if (typeof (packet) === 'string' && packet.trim().startsWith("<")) {
        $('#JEPrepMainPage').html('');
        $('#RoutingDialog').html('');
        $('#PreparerRoutingDialog').html('');
        $('#JEPrepMainPage').html(packet);
    }
    // Clear status from JE prep screen on page refresh
    $('#ImportStatusPanelBar').hide();
    $("#journalStatus").show();
    $("#journalErrorMessage").html("");
    registerPageLoadEvents();
}

/**** AJAX GENERAL RESPONSE HANDLING ============================================================================= ****/

function AjaxGeneralSuccess(packet, textStatus, jqXHR) {
    //Expects packet to be a JEPrepAjaxGeneralResponse object, currently defined in JEPrepController.
    var removeErrorIconFromScreen = function() {
        
        $('p.messageIconError').removeClass('messageIconError');
        $("#journalErrorMessage table colgroup col:first").attr('width', 1);

    };
    if (packet.ImportStatusId) {
        var panel = $("#ImportStatusPanelBar").data("tPanelBar");
        var item = $("li:first", panel.element)[0];
        ChangePBImage('images/slider_loading.gif');
        ChangePBText($('#ReconResource_ValidatingJournal').val());
        $('#ImportStatusPanelBar').show();
        $("#journalStatus").show();
        $("#journalErrorMessage").html("");
        EnableButtons();
        DisableSaveValSubmitEdit();
        intervalId = setInterval(function () { updateStatus(packet.ImportStatusId); }, 3000);
        return; //only stop if errors
    }

    if (packet.HasErrorsForFields) {
        JEHighlightFieldErrors(packet.FieldErrorList);
        SetErrClassForReversalPeriod(packet.FieldErrorList);
        if (packet.HasPageMessage) {
            $('#JEPrepPageMsg').show();
            $('#JEPrepPageMsg').html(packet.PageMessageFormattedWithIcon);
        }
        EnableButtons();
        return; //we may not want to return here -- can you have field-level errors AND a page message or popup?
    }

    /* Discontinue use of ReconRevision/_AUD for JE */
    //UpdateReconRevisions(packet);

    if (packet.HasPopupMessage) {
        OpenMessageDialog(packet.PopupMessageFormattedWithoutIcon, packet.PopupTitle);
        if (packet.HasErrorsForPopup) {
            EnableButtons();
            return; //only stop if errors
        }
    }
    
    //Some actions continue on to further processing which can involve more ajax or other functions. 
    //If we have errors we do not want to do that, we want to stop here.
    if (packet.HasErrorsForAnything) {
        //do not go on to further actions
    }
    else {
        if (packet.ButtonOrActionName == 'submitpreprocessing') {
            if (packet.HasConfirmMessage) {
                var okLabel = $('#okLabel').text();
                var continueLabel = $('#continueLabel').text();
                $('.confirmDialog .ui-button-text:contains(' + okLabel + ')').text(continueLabel);
                JEPrepOpenConfirmDialog(packet.ConfirmTitle,
                    packet.ConfirmMessageFormattedWithIcon,
                    function () { JEActionWithEmailForm("submit"); });
                EnableButtons();
                return;
            }
            else {
                JEActionWithEmailForm("submit");
                EnableButtons();
                return;
            }
        }
        if (packet.ButtonOrActionName == 'submitNextPreparer') {
            JEActionWithEmailForm(packet.ButtonOrActionName);
            EnableButtons();
            return;
        }
        if (packet.ButtonOrActionName == 'savethenapproutingpopup') {
            JEPrepApproverRoutingClicked();
            EnableButtons();
            return;
        }
        if (packet.ButtonOrActionName == 'savethenpreproutingpopup') {
            JEPrepPreparerRoutingClicked();
            EnableButtons();
            return;
        }
    }

    if (packet.HasPanelMessage) {
        ChangePBImage('images/Toolbar/cancel.gif');
        ChangePBText($('#JE_ErrorValidatingJournal').val());
        $("#journalErrorMessage").html("<p style=\"margin: 0px 5px 5px 5px;\">" + packet.PanelMessageFormattedWithIcon.replace('</span><br />Criteria</th>', '</span> Criteria</th>') + "</p>");
        var panel = $("#ImportStatusPanelBar").data("tPanelBar");
        var item = $("li:first", panel.element)[0];

        //Not expand the panel if the panel is already expanded
        if ($(item).hasClass('t-state-default')) {
            panel.expand(item);
        }
        
        $('#ImportStatusPanelBar').show();
        $("#journalStatus").show();
        EnableButtons();
        removeErrorIconFromScreen();
        return; //only stop if errors
    }

    if (packet.HasPageMessage) {
        $('#JEPrepPageMsg').show();
        $('#JEPrepPageMsg').html(packet.PageMessageFormattedWithIcon);
        EnableButtons();
        return;
    }

    if (packet.SubmitDialogNeeded) {
        var dialogObj = $('#JEPrep_Submit_Post_Dialog_2way');
        if (packet.SubmitDialogShowPostLaterButton == true) {
            dialogObj = $('#JEPrep_Submit_Post_Dialog_3way');
        }
        dialogObj.dialog({ title: packet.SubmitDialogTitle });
        dialogObj.html(packet.SubmitDialogText);
        dialogObj.dialog('open');
        EnableButtons();
        return;
    }

    //Note that you may not want to go to dashboard if you had errors on the current page.  We can talk this out later, or just leave to developer to set the GoToDashboard flags correctly.
    if (packet.GoToDashboard) {
        window.location = $('#JEPrepDashboardURL').val();
        EnableButtons();
        return;
    }


}


function isJEPrepFormValid() {
    return $('#JEPrepForm').validate().form();
}

/**** BUTTON-CLICK EVENTS ==================================================================================== ****/

function JEActionWithWholeForm(actionName) {
    if (!isJEPrepFormValid()) {
        return;
    }

    resetPageMessage();
    JEResetValidationErrors();

    //set hidden field to the action ("submit" or "validate" or etc.) so that the form serialize picks it up
    $('#jeAction').val(actionName);

    var selectedPeriod = $('#Period').val();
    $('#SelectedPeriod').val(selectedPeriod);
    
    var selectedReversalPeriod = $('#ReversalPeriod').val();
    $('#SelectedReversalPeriod').val(selectedReversalPeriod);

    var selectedTemplate = $('#Template').val();
    $('#SelectedTemplate').val(selectedTemplate);
    var origSelectedTemplate = $('#OrigTemplateId').val();
    $('#OrigSelectedTemplate').val(origSelectedTemplate);

    if (actionName == "reverseccy" | selectedTemplate != $('#OrigTemplateId').val())
    {
        JEActionWhithWholeFormWithRefresh(actionName);
    }    
    else {
        var disabled = $('#JEPrepForm').find(':input:disabled').removeAttr('disabled');
        var formData = $('#JEPrepForm').serialize();      
        disabled.attr('disabled', 'disabled');
        $.ajax({
            type: "post",
            url: $('#JEPrepGeneralActionWithWholeFormURL').val(),
            data: formData,
            beforeSend: function () {
                $('#spinnerPane').slideDown();
            },
            success: AjaxGeneralSuccess,
            error: DisplayTrintechAjaxError,
            complete: function () {
                $('#spinnerPane').slideUp();
            },
            cache: false
        });
    }
}

function PreparePageForPostBack(actionName) {
    resetPageMessage();
    JEResetValidationErrors();

    //set hidden field to the action ("submit" or "validate" or etc.) so that the form serialize picks it up
    $('#jeAction').val(actionName);

    //trigger page validation first
    var isValid = $('#JEPrepForm').validate().form();  //var isValid = $('#JEPrepForm').validate().valid();
    if (!isValid) {
        return;
    }
    var selectedPeriod = $('#Period').val();
    $('#SelectedPeriod').val(selectedPeriod);
    var selectedReversalPeriod = $('#ReversalPeriod').val();
    $('#SelectedReversalPeriod').val(selectedReversalPeriod);
    var selectedTemplate = $('#Template').val();
    $('#SelectedTemplate').val(selectedTemplate);
}

function JEActionWhithWholeFormWithRefresh(actionName) {
    var disabled = $('#JEPrepForm').find(':input:disabled').removeAttr('disabled');
    var formData = $('#JEPrepForm').serialize();   
    disabled.attr('disabled', 'disabled');
    $.ajax({
        type: "post",
        url: $('#JEPrepGeneralActionWithWholeFormURL').val(),
        data: formData,
        success: JERefreshPrepPageSuccess,
        error: DisplayTrintechAjaxError,
        cache: false
    });
    
    JERefreshPrepPage();
}

function JEDeleteAction() {
    var deleteJETitle = $('#deleteJE').text();
    var yesLabel = YesResourceLabel();
    var noLabel = NoResourceLabel();
    var buttonsArray = {};
    buttonsArray[yesLabel] = function () {
                        JEActionWithoutWholeForm("delete");
                        $('#dialogconfirmdeleteJE').dialog("close");
                    };
    buttonsArray[noLabel] = function () {
        $('#dialogconfirmdeleteJE').dialog("close");
        return;
    };

    $('#dialogconfirmdeleteJE').dialog(
            {
                autoOpen: false,
                modal: true,
                height: 140,
                stack: true,
                zIndex: 10000,
                title: deleteJETitle,
                resizable: false,
                buttons: buttonsArray
            });
            
            $('#dialogconfirmdeleteJE').dialog('open');
            $('#dialogconfirmdeleteJE').dialog('moveToTop');
           
}

function JEActionWithoutWholeForm(buttonOrActionName) {
    resetPageMessage();
    JEResetValidationErrors();
    //include antiforgerytoken in ajax post
    var token = $('input[name=__RequestVerificationToken]').val();
    var jeId = $('#Id').val();
    var packet = { jeId: jeId, buttonOrActionName: buttonOrActionName, '__RequestVerificationToken': token };  //we simply send the JE and the action

    $.ajax({
        url: $('#JEPrepGeneralActionURL').val(),
        type: 'post',
        data: packet,
        datatype: 'json',
        beforeSend: ShowSpinner,
        complete: HideSpinner,
        success: AjaxGeneralSuccess,
        error: DisplayTrintechAjaxError,
        cache: false
    });
}

function DisablePrepMenu() {
    processing = true;
}

function EnablePrepMenu() {
    processing = false;
}

function ShowSpinner() {
    DisablePrepMenu();
    $('#spinnerPane').slideDown();
}

function HideSpinner() {
    $('#spinnerPane').slideUp();
    EnablePrepMenu();
}

function JESubmitPostingDecisionFromUI(postingOption) {
    var jeId = $('#Id').val();
    var emailPreparerCheckbox = $('#EmailPreparerCheckbox').is(":checked");
    var comments = $('#EmailComments').val();
    var subject = $('#EmailSubject').val();
    var emailOthersCheckbox = $('#EmailOthersCheckbox').is(":checked");
    var toList = $('#EmailToList').val();
    var ccList = $('#EmailCCList').val();
    var auditTrailCheckbox = $('#AuditTrailCommentsCheckbox').is(":checked");
    var nextRoleEmail = $('#NextRoleEmail').val();
    var currentUserFullName = $('#CurrentUserFullName').val();
    //include antiforgerytoken in ajax post
    var token = $('input[name=__RequestVerificationToken]').val();
    var formData = {
        jeId: jeId, 
        postingOption: postingOption,
        emailPreparerCheckbox: emailPreparerCheckbox,
        Comments: comments,
        subject: subject,
        emailOthersCheckbox: emailOthersCheckbox,
        toList: toList,
        ccList: ccList,
        auditTrailCheckbox: auditTrailCheckbox,
        IsEmailNextRoleChecked: emailPreparerCheckbox,
        IsEmailOthersChecked: emailOthersCheckbox,
        IsAuditTrailCommentsChecked: auditTrailCheckbox,
        NextRoleEmail: nextRoleEmail,
        EmailToList: toList,
        EmailCCList: ccList,
        EmailSubject: subject,
        CurrentUserFullName: currentUserFullName,
        '__RequestVerificationToken': token
    };

    $.ajax({
        type: "post",
        url: $('#JEPrepSubmitPostingDecisionFromUIURL').val(),
        data: formData,
        success: AjaxGeneralSuccess,
        error: DisplayTrintechAjaxError,
        cache: false
    });
}

/**** Email Common =========================================================================================== ****/

var emailModal;

function JEActionWithEmailForm(actionName) {
    var jeId = $('#Id').val();
    var title = GetEmailDialogTitle(actionName);

    $.ajax({
        type: "get",
        url: GetEmailDialogURL(actionName),
        data: {
            jeId: jeId
        },
        success: function (packet) {
            openEmailDialog(packet, title, actionName, jeId);
        },
        error: DisplayTrintechAjaxError,
        cache: false
    });
}

function GetEmailDialogURL(actionName) {
    switch (actionName) {
        case "reject":
            return $('#JEPrepRejectEmailModalURL').val();
        case "approve":
            return $('#JEPrepApproveEmailModalURL').val();
        case "submit":
            return $('#JEPrepSubmitEmailModalURL').val();
        case "submitNextPreparer":
            return $('#JEPrepNextPreparerEmailModalURL').val();
    }
}

function JEPrepEmailSubmitCallback(action, jeId) {
    if (action === 'submitNextPreparer') {
        return function (data) {
            data += "&IsEmailNextRoleChecked=" + $('#EmailPreparerCheckbox').is(":checked");
            data += "&IsEmailOthersChecked=" + $('#EmailOthersCheckbox').is(":checked");
            data += "&IsAuditTrailCommentsChecked=" + $('#AuditTrailCommentsCheckbox').is(":checked");
            data += "&jeId=" + jeId;

            $.ajax({
                type: "post",
                url: $('#JEPrepSubmitNextPreparerURL').val(),
                data: data,
                beforeSend: function () { $('#spinnerPaneEmail').slideDown(); },
                success: AjaxGeneralSuccess,
                error: DisplayTrintechAjaxError,
                complete: function () { $('#spinnerPaneEmail').slideUp(); emailModal.closeModal(); },
                cache: false
            });
        };
    } 

    return function () {
        var emailPreparerCheckbox = $('#EmailPreparerCheckbox').is(":checked");
        var comments = $('#EmailComments').val();
        var subject = $('#EmailSubject').val();
        var emailOthersCheckbox = $('#EmailOthersCheckbox').is(":checked");
        var toList = $('#EmailToList').val();
        var ccList = $('#EmailCCList').val();
        var auditTrailCheckbox = $('#AuditTrailCommentsCheckbox').is(":checked");
        var formData = '';

        var url = '';

        if (action == "reject" || action == "approve") {

            url = $('#JEPrepEmailSaveURL').val();

            formData = {
                jeId: jeId,
                emailPreparerCheckbox: emailPreparerCheckbox,
                buttonOrActionName: action,
                comments: comments,
                subject: subject,
                emailOthersCheckbox: emailOthersCheckbox,
                toList: toList,
                ccList: ccList,
                auditTrailCheckbox: auditTrailCheckbox
            };
        }
        else if (action == "submit") {
            $('#emailPreparerCheckbox').val(emailPreparerCheckbox);
            $('#Comments').val(comments);
            $('#subject').val(subject);
            $('#emailOthersCheckbox').val(emailOthersCheckbox);
            $('#toList').val(toList);
            $('#ccList').val(ccList);
            $('#auditTrailCheckbox').val(auditTrailCheckbox);
            $('#jeAction').val(action);
            var selectedPeriod = $('#Period').val();
            $('#SelectedPeriod').val(selectedPeriod);
            var selectedReversalPeriod = $('#ReversalPeriod').val();
            $('#SelectedReversalPeriod').val(selectedReversalPeriod)
            var selectedTemplate = $('#Template').val();
            $('#SelectedTemplate').val(selectedTemplate);
            var form = $('#JEPrepForm').serialize();
            formData = form;
            url = $('#JEPrepSubmitEmailSaveURL').val();

            formData += "&IsEmailNextRoleChecked=" + $('#EmailPreparerCheckbox').is(":checked");
            formData += "&IsEmailOthersChecked=" + $('#EmailOthersCheckbox').is(":checked");
            formData += "&IsAuditTrailCommentsChecked=" + $('#AuditTrailCommentsCheckbox').is(":checked");
            formData += "&jeId=" + jeId;
            formData += "&NextRoleEmail=" + $('#NextRoleEmail').val();
            formData += "&EmailToList=" + toList;
            formData += "&EmailCCList=" + ccList;
            formData += "&EmailSubject=" + subject;
            formData += "&CurrentUserFullName=" + $('#CurrentUserFullName').val();

        }

        $.ajax({
            type: "post",
            url: url,
            data: formData,
            datatype: 'json',
            beforeSend: function () { $('#spinnerPaneEmail').slideDown(); },
            success: AjaxGeneralSuccess,
            error: DisplayTrintechAjaxError,
            complete: function () { $('#spinnerPaneEmail').slideUp(); emailModal.closeModal(); },
            cache: false
        });
    };
}

function openEmailDialog(packet, title, action, jeId) {
    emailModal = JEEmailDialog($('#EmailConfirmDialog'));
    emailModal.open(
        packet,
        {
            submit: JEPrepEmailSubmitCallback(action, jeId),
            cancel: emailModal.closeModal
        },
        title
    );
}

/**** Email Common  =========================================================================================== ****/

/**** Import Begin   =========================================================================================== ****/

$(function () {
    $('#ImportDialog').dialog(
        { autoOpen: false,
            modal: true,
            resizable: false,
            zIndex: 10000,
            width: 750,
            height: 450,
            draggable: true
        })
});

function ImportClicked() {
    JEPrepImportPopupGet();
}

function JEPrepImportPopupGet() {
    var jeId = $('#Id').val();
    var packet = { jeId: jeId }
    $.ajax({
        type: "get",
        url: $('#JEPrepImportURL').val(),
        success: ImportDialogOpen,
        data: packet,
        error: DisplayTrintechAjaxError,
        cache: false
    });
}

function ImportDialogOpen(packet) {
    $('#ImportDialog').html(packet);
    $('#ImportDialog').dialog('open');
}

/**** Import End   =========================================================================================== ****/

/**** JE Batch Records Begin   =========================================================================================== ****/

$(function () {
    $('#JEBatchRecord').dialog(
        { autoOpen: false,
            modal: true,
            resizable: false,
            zIndex: 10000,
            width: 750,
            height: 450,
            draggable: true
        })
});

/**** JE Batch Records End   =========================================================================================== ****/

/**** ROUTING =========================================================================================== ****/

var preparerRoutingDialog = new PreparerRoutingDialog(
    $("#PreparerRoutingDialog"),
    $('#JEPreparerRoutingPreparerChangedURL').val(),
    {
        titles: {
            error: $('#ErrorTitle').val()
        }
    }
);

function JEPrepPreparerRoutingClicked() {
    var jeId = $('#Id').val();

    $.ajax({
        type: 'get',
        url: $('#JEPrepPreparerRoutingURL').val(),
        data: { jeId : jeId },
        success: preparerRoutingDialog.openDialog,
        error: DisplayTrintechAjaxError,
        cache: false
    });
}

function JEPrepApproverRoutingClicked() {

    //in case we want to add dialog here reminding them to save changes first etc

    //this is what they would do if they continued
    JEPrepApproverRoutingPopupGet();
}

function JEPrepApproverRoutingPopupGet() {

    var jeId = $('#Id').val();
    var cameFrom = 'jeprep';
    var packet = { jeId: jeId, cameFrom: cameFrom };

    $.ajax({
        type: "get",
        url: $('#JEPrepApproverRoutingURL').val(),
        data: packet,
        success: RoutingDialogOpen,
        error: DisplayTrintechAjaxError,
        cache: false
    });
}

function RoutingDialogOpen(packet) {
    $('#JERoutingCallingPageShouldRefresh').val('False');
    $('#RoutingDialog').html(packet);
    $('#RoutingDialog').dialog('open');
}

function RoutingDialogClose() {
    //Do nothing here.   Other function handles exact actions that should be taken after close.
}

function JERoutingDialogPostCloseProcessingUniqueToCallingPage() {
    var jeRoutingDialogRecommendedRefresh = $('#JERoutingCallingPageShouldRefresh').val();
    if (jeRoutingDialogRecommendedRefresh == "True") {
        var location = window.location;
        window.location = location;
    }
}


/**** AUDIT TRAIL dialog ==================================================================================== ****/

function JEPrepAuditTrailClicked(event) {
    var jeId = $('#Id').val();
    var cameFrom = 'jeprep';
    var packet = { jeId: jeId, cameFrom: cameFrom };

    $.ajax({
        url: $('#JEPrepAuditTrailURL').val(),
        type: 'post',
        data: packet,
        dataType: 'html',
        success: JEPrepAuditTrailSuccess,
        error: DisplayTrintechAjaxError,
        async: false,
        cache: false
    });
}

function JEPrepAuditTrailSuccess(packet) {
    $('#JEAuditTrailDialog').html(packet);
    $('#JEAuditTrailDialog').dialog('open');
}

function CloseAuditTrailDialog() {
    $('#JEAuditTrailDialog').dialog('close');
}

/**** NOTES management ==================================================================================== ****/

function CreateNote() {
     CreateNoteOnServer();
}

function CloseNotesDialog() {
    $('#NotesDialog').empty();
    $('#NotesDialog').dialog('close');
    extendValidatorMessagesForMainPage();
}

function CreateNoteOnServer() {
    var formData = $('#NotesDialog form').serialize();
    //include antiforgerytoken in ajax post
    var token = $('input[name=__RequestVerificationToken]').val();
    formData.push({ name: '__RequestVerificationToken', value: token });
    $.ajax({
        type: "post",
        url: JEDashboardCreateNoteURL(),
        data: formData,
        success: CreateNoteResponse,
        error: DisplayTrintechAjaxError,
        cache: false
    });
}

function CreateNoteResponse(packet) {
    if (packet.HasError) {
        $('#NotesDialog form').validate().showErrors(packet.ErrorArray);
        return;
    }
    if (packet.HasException) {
        alert(packet.ExceptionText);
        return;
    }
}

function JEPrepOpenConfirmDialog(title, message, successFunction) {
    var dialogObj = $('#JEPrep_Confirm_Dialog');
    dialogObj.dialog({ title: title });
    dialogObj.html(message);
    dialogObj.data('successFunction', successFunction);
    dialogObj.dialog('open');
}

function GetJENotesContent(event) {
    var jeId = $('#Id').val();
    var packet = { jeId: jeId };
    $.ajax({
        type: "get",
        url: JENotesURL(),
        data:packet,
        cache: false,
        error: DisplayTrintechAjaxError,
        success: function (data) {
            $('#NotesDialog').empty();
            $('#NotesDialog').append(data);
        }
    });
    $('#NotesDialog').dialog('open'); 
}

function UpdateNotesCountAndRefresh(packet) {
    if (packet.HasError) {
        $('#NotesDialog form').validate().showErrors(packet.ErrorArray);
        return;
    }
    $('#AddNoteDiv').hide();
    $('#JEPrepCreateNotes span').contents(':last').replaceWith(packet.noteCount);
    GetJENotesContent(packet);

}

/****GRID functions part 1 ====================================================================================****/

function JEPrepAddRemoveRowClicked(event, action) {
    var rowCount = $('.JEPrepRow').not('.JEPrepRowTemplate').size();

    //Don't allow last row to be deleted
    if (action == 'remove') {
        if (rowCount < 2) { return; } //Accounts for hidden template row
        JEPrepRemoveRow(event);
        updateDrCrTotals();
        updateDynConversionAmount();
        return;
    }
    
    if (action == 'add') {
        //Don't allow more than 999 rows.
        if (!CanAddRow()) { return; }
        var clickRowId = $(event.target).parents('tr').attr('id');
        JEPrepAddRow(clickRowId, null);
        InitializeAutocomplete();
        updateDrCrTotals();
        updateDynConversionAmount();
        return;
    }
}

function CanAddRow() {
    //Accounts for hidden template row
    var rowCount = $('.JEPrepRow').not('.JEPrepRowTemplate').size();
    return rowCount < 999;
}

function JEPrepAddRow(clickRowId, newRowIdParm) {
    var jeId = $('#Id').val();

    var nextId = newRowIdParm;
    if (newRowIdParm == null) {
        var nextIdString = $('#JEPrepNextId').val();

        //Increment next ID for next use
        var currentIdInt = parseInt(nextIdString);
        currentIdInt++;
        $('#JEPrepNextId').val(currentIdInt);
        nextId = 'NEW' + nextIdString;
    }

    var templateRow = $('.JEPrepRowTemplate');
    var templateClone = templateRow.clone();

    //Modify JEPrepRow_-1 to JEPrepRow_2
    var oldRowIDArray = $(templateClone).attr('id').split("_");
    var newRowID = oldRowIDArray[0] + '_' + nextId;
    templateClone.attr('id', newRowID);

    //Modify name & ID of each cell
    templateClone.find('input.JEPrepCell').each(function (index) {
        oldIDArray = $(this).attr('id').split("_");
        if (oldIDArray[1] == "-1") {
            $(this).attr('id', cellPrefix + nextId + '_' + oldIDArray[2]);
            $(this).attr('name', cellPrefix + nextId + '_' + oldIDArray[2]);
        }

        //Add class to note that the cell is editable.  This will enable validation for the cell.
        var colNum = $(this).attr('data-JEPrepColNum');
        $(this).addClass('JEPrepEditCol' + colNum);
    });

    //Remove template class.
    templateClone.removeClass('JEPrepRowTemplate');

    //Insert row into table.
    if (clickRowId) {
        var row = $('#' + clickRowId);
        templateClone.insertAfter(row);
    }
    else {
        $('#JEPrepTable tr:last').after(templateClone);  //Used when clearing all rows.
    }

    //Register buttons on row.
    registerJEPrepGridButtons(templateClone);
    registerCCYFields(templateClone);
    JEPrepSetLastCellClass();
}

function JEPrepRemoveRow(event) {
    $(event.target).parents('tr').remove();
    JEPrepSetLastCellClass();
}

function JEPrepSetLastCellClass() {
    $('.JEPrepLastCell').each(function (index, element) { $(this).removeClass('JEPrepLastCell'); });
    var lastPrepRow = $('.JEPrepRow').not('.JEPrepRowTemplate').last();
    var lastCell = lastPrepRow.find('td[class!="JEPrepReadOnlyTD"]:last').find('input.JEPrepCell');
    
    lastCell.addClass('JEPrepLastCell');
}

function JEPrepClearGridClicked(event) {
    var title = $('#clearAllGridLabel').text();
    var body = $('#permDeletedLabel').text();
    JEPrepOpenConfirmDialog(title, body, function () { JEPrepClearGrid() });
}

function JEPrepClearGrid() {
    var jeId = $('#Id').val();
    //include antiforgerytoken in ajax post
    var token = $('input[name=__RequestVerificationToken]').val();
    var packet = { jeId: jeId, '__RequestVerificationToken': token };
    $.ajax({
        type: "post",
        url: $('#JEPrepClearGridURL').val(),
        data: packet,
        success: JERefreshPrepPageSuccess,
        error: DisplayTrintechAjaxError,
        cache: false
    });
}

/****GRID functions part 2 ====================================================================================****/

function registerJEGridEvents() {
    $('#JEPrepTable').keydown(function (e) {
        JEGridKeystroke(e);
    });
    $('#JEPrepTable').dblclick(function (e) {
        JEGridDblClick(e);
    });
    $('#JEPrepTable').bind('paste', (function (e) {
        e.preventDefault();
        JEGridPaste(e);
    }));
//    $('table.JEPrepGrid input').bind('paste', (function (e) {
//        JEGridPaste(e);
//    }));
    $('table.JEPrepGrid input').focus(function (e) {
        JEGridGetFocus(e);
    });
    $('table.JEPrepGrid input').blur(function (e) {
        JEGridLoseFocus(e);
    });

    //    $('.autoCompleteColumn').autocomplete({
    //        source: function (request, response) {
    //            autoCompleteAjax(request, response, "Some Field Data");
    //        },
    //        open: function (event, ui) {
    //            $(event.target).addClass('excelEdit');
    //        },
    //        close: function (event, ui) {
    //            $(event.target).removeClass('excelEdit');
    //        },
    //        disabled: true
    //    });
}

function JEGridKeystroke(event) {
    var target = $(event.target);
    var targetId = target.attr('id');
    if (targetId == null) return;
    var targetFieldId = targetId.split('_')[2];
    var parentRow = $(event.target).parents('.JEPrepRow');
    var newCellId;
    var newCell;

    switch (event.keyCode) {
        case 13: //Enter
            if ($(event.target).hasClass('excelEdit')) {
                $(event.target).removeClass('excelEdit');
            }
            break;
        case 38: //Up
            if ($(event.target).hasClass('PickList')) {
                return;
            }
            var prevRow = parentRow.prev().attr('id');
            if (prevRow != null) {
                var prevRowGuid = parentRow.prev().attr('id').split('_')[1];
                newCellId = cellPrefix + prevRowGuid + '_' + targetFieldId;

            }
            break;
        case 39: //Right
            if (target[0].type != "text" || target[0].selectionStart >= target.context.value.length) {
                var newCellId = target.parent('td').nextAll('[class!="JEPrepReadOnlyTD"]').first().find('.JEPrepCell').attr('id');
            }
            break;
        case 40: //Down
            if ($(event.target).hasClass('PickList')) {
                return;
            }
            var nextRow = parentRow.next().attr('id');
            if (nextRow != null) {
                var nextRowGuid = parentRow.next().attr('id').split('_')[1];
                newCellId = cellPrefix + nextRowGuid + '_' + targetFieldId;

            }
            break;
        case 37: //Left
            if (target[0].type != "text" || target[0].selectionStart == 0) {
                var newCellId = target.parent('td').prevAll('[class!="JEPrepReadOnlyTD"]').first().find('.JEPrepCell').attr('id');
            }
            break;
        case 9:
            if (target.hasClass('JEPrepLastCell')) {
                if (CanAddRow() && !event.shiftKey) {
                    var parentRowId = parentRow.attr('id');
                    JEPrepAddRow(parentRowId, null);
                    updateDrCrTotals();
                    updateDynConversionAmount();
                    InitializeAutocomplete();
                }
            }
            break;
    }

    if ((newCellId != null) && (!$(event.target).hasClass('excelEdit'))) {
        var newCell = $('#' + newCellId);
        if ($(newCell).length > 0) {
            //$(event.target).blur();  //For non-IE
            newCell.focus();
        }
        event.preventDefault();
    }
}

function JEGridPaste(event) {
    event.preventDefault();
    pasteExcel(event);
}

function JEGridDblClick(event) {
    $(event.target).addClass('excelEdit');
}
function JEGridGetFocus(event) {
    if ($(event.target).hasClass('autoCompleteColumn')) {
        $(event.target).autocomplete("enable");
    }
}
function JEGridLoseFocus(event) {
    if ($(event.target).hasClass('autoCompleteColumn')) {
        $(event.target).autocomplete("disable");
    }

    $(event.target).removeClass('excelEdit');
}

function pasteExcel(event) {
    // Perform paste operation if detail grid is in edit mode.
    var enableDetailGrid = $('#SecEnableDetailGrid').val();
    if (enableDetailGrid == "True") {
        var targetId = $(event.target).attr('id');
        if (targetId.indexOf('JEPrepCell') == -1) return;
        var nextIdString = $('#JEPrepNextId').val();
        var targetArray = targetId.split('_');
        var rowIdList = '';
        $('.JEPrepRow').each(function (index, element) { rowIdList = rowIdList.concat($(element).attr('id') + ';'); });
        var text;
        if (window.clipboardData) { //IE
            text = clipboardData.getData('Text');
        } else {
            text = (event.originalEvent || event).clipboardData.getData('text/plain');
        }

        // Fix IE11 issue with paste getting Access Denied error
        if (isIE11()) {
            setTimeout(function () {
                postJEPrepPasteData(text, targetArray, nextIdString, rowIdList);
            }, 1);
        } else {
            postJEPrepPasteData(text, targetArray, nextIdString, rowIdList);
        }
    }
}

function postJEPrepPasteData(text, targetArray, nextIdString, rowIdList) {
    $.ajax({
        type: "post",
        url: $('#JEPrepPasteURL').val(),
        data: { jeId: $('#Id').val(), clipboardData: text, gridName: targetArray[0], detailRowId: targetArray[1], detailRowFieldDefId: targetArray[2], nextId: nextIdString, rowIdList: rowIdList },
        success: pasteExcelResponse,
        error: DisplayTrintechAjaxError,
        cache: false
    });
}


function isIE11() {
    var userAgent = window.navigator.userAgent;
    if (!!userAgent.match(/Trident\/7\./))
        return true;
    else
        return false;
}

function pasteExcelResponse(packet) {
    if (packet.HasError) {
        alert(packet.ErrorMessage);
        return;
    }

    var neighborRowId = packet.LastExistingRowId;
    $.each(packet.NewRowIds, function (index, rowId) {
        JEPrepAddRow(neighborRowId, rowId);
        neighborRowId = 'JEPrepRow_' + rowId;
    });

    $(packet.CellData).each(function (i) {
        var id = this.CellId;
        var content = this.Content;
        var element = $('#' + id);

        if (element.attr('type') == "checkbox")
        {
            if (content.toLowerCase() == "false"
                || content == "0")
            {
                element.prop('checked', false);
            }
            else
            {
                element.prop('checked', true);
            }
        }
        else
        {
            element.val(content);
        }
    });

    //Set next ID for new rows
    $('#JEPrepNextId').val(packet.NextId);

    //Update row shading
    $('.JEPrepRow').each(function (i, eachRow) { CCYFieldChanged(eachRow) });
    updateDrCrTotals();
    updateDynConversionAmount();
    InitializeAutocomplete();
}

//function autoCompleteAjax(request, response, myData) {
//    $.ajax({
//        url: "Excel/AutoComplete",
//        data: {
//            eventData: myData,
//            term: request.term
//        },
//        success: function (packet) {
//            return autoCompleteResponse(response, packet);
//        }
//    });
//}

//function autoCompleteResponse(response, packet) {
//    response($.map(packet, function (item) {
//        return {
//            id: item.id,
//            label: item.label,
//            value: item.label
//        }
//    }))
//}

function JEDetailExportToExcel() {
    BodyBusy();
    DisableButtons();
    $.ajax({
        async: false,
        type: "get",
        url: $('#JEPrepExportToExcelURL').val(),
        success: function () {
            BodyDefault();
            EnableButtons();
        },
        error: function (jqXHR, textStatus, errorThrown) {
            BodyDefault();
            EnableButtons();
            DisplayTrintechAjaxError(jqXHR, textStatus, errorThrown);
        },
        cache: false
    });    
}


function setupConfirmReopenDialog() {
    $('#ConfirmReopenDialog').dialog(
        {
            autoOpen: false,
            modal: true,
            resizable: false,
            width: 'auto',
            height: 'auto',
            zIndex: 10000,
            open: function () {
                var buttons = $('#ConfirmReopenDialog').parent().find('button');
                buttons.removeClass('ui-button ui-state-default ui-corner-all ui-button-text-only ui-widget');
                // recenter dialog on open
                $(this).dialog('widget').position({ my: "center", at: "center", of: window });
            }
        });
}


function JEPrepReopenButtonClicked() {

    var data = { jeId: $('#Id').val() };

    $.ajax({
        data: data,
        url: $('#JEPreparerRoutingReopenURL').val(),
        success: function (result) {
            $('#ConfirmReopenDialog').html(result);
            $('#ConfirmReopenDialog').dialog('open');
        },
        error: DisplayTrintechAjaxError,
    });
}


function JEPrepReverseButtonClicked(event) {
    $('#ReverseJEDialog').dialog('open');
}
function ReverseSelected() {
    var isValid = $('#ReverseJEDialog form').validate().form();
    if (isValid) {
        var revPostingDate = formatDate($('#ReversePostingDate').data('tDatePicker').value(), null);
        if (revPostingDate == "null") { }
        else {
            ResetReverseJEErrors();
            resetPageMessage();
            var revPeriod = $('#ReversePeriodSelectList').val();

            var packet = { id: $('#Id').val(), newFinancialPeriod: revPeriod, reversePostingDate: revPostingDate };
            $.ajax({
                type: "post",
                data: packet,
                url: $('#JEPrepReverseURL').val(),
                dataType: 'json',
                success: SuccessReverse,
                error: DisplayTrintechAjaxError,
                cache: false
            });
        }
    }
}


function CloseReverseDialog() {
    $('#ReverseJEDialog').dialog('close');
}
function SuccessReverse(responseObj) {
    if (responseObj.HasErrorsForPage) {
        CloseReverseDialog();
        $('#JEPrepPageMsg').show();
        $('#JEPrepPageMsg').html(responseObj.PageMessageFormattedWithIcon);
        return;
    }
    else
    {
        CloseReverseDialog();
    }
}

function formatDate(date, format) {
    format = format || '{0:d}';
    return $.telerik.formatString(format, date);
}

function GetSelectedRevision() {
    var rev = $('#RevisionSelectList').val();
    var packet = { jeId: $('#Id').val(), revision: rev };
     $.ajax({
        type: "get",
         url: $('#JEPrepGetRevisionURL').val(),
        data: packet,
        success: JERefreshPrepPageSuccess,
        error: DisplayTrintechAjaxError,
        cache: false
    });
}

function HideAllMenuButtons() {
    $('#JEPrepMenu').children('*').hide();
    //always enable nav button
    $('#JEStatusNavButton').show();
}

function DisableNameField() {
    $('#Name').attr('disabled', 'disabled');
}

function DisableHeader() {
    // set fields to readonly so that user can still click in the field and see/select text if need be
    // have to manual set any checkbox and template, period dropdowns to disabled (dropdowns do not have readonly attribute.)
    $('#JeTitle').find('#Template').attr('disabled', 'disabled');
    $('#JeTitle').find('#Period').attr('disabled', 'disabled');
    $('#JeTitle').find('#ReversalPeriod').attr('disabled', 'disabled');
    $('#JeTitleAndPrep').find(':input[class$=" JEPrepBool"]').attr('disabled','disabled');
    $('#JeTitleAndPrep').find(':input').attr('readonly', 'readonly');
}

function HideHeaderData() {
   // Hide Menu, footer and header part from JE Preparation page if journal entry show in read-only mode.
    if ($('#JEReadOnlyView').val().toLowerCase() == 'true') {
        $('#header').hide();
        $('#menu_nav_header').hide();
        $('#MVCfooter').hide();
    }
}

function DisableGrid() {
    // set fields to readonly so that user can still click in the field and see/select text if need be
    // have to manual set any checkbox to disabled (checkbox does not have readonly attribute.)
    $('#JEPrepTable tbody').find('*').attr('readonly', 'readonly');
    $('#JEPrepTable').find(':input[class$="JEPrepBool"]').attr('disabled', 'disabled');
    // Set checkbox to readonly if it is last cell on je prepartion grid.
    $('#JEPrepTable').find(':input[class$="JEPrepBool JEPrepLastCell"]').attr('disabled', 'disabled');
    $('#JEPrepAddRow pointer').attr('disabled', true);
    $('#JEPrepDeleteRow pointer').attr('disabled', true);
}

function EnableControlAudit(){
    $('#RevisionSelectList').removeAttr('disabled');  
}

function EnableControlPostingDate() {
    $('input[class$=" JEPrepDate"]').removeAttr('disabled');
}

function HidePostingDate() {
    $('input[class$=" JEPrepDate"]').hide();
}

function EnableControlSave() {
    $('#JEPrepMenu').find('#JEPrepSaveButton').removeAttr('disabled');
}

function EnableControlPeriod() {
    $('#Period').removeAttr('disabled');
}
function DisableControlPeriod() {
    $('#Period').attr('disabled', 'disabled');
}

function EnableControlReversalPeriod() {
    $('#ReversalPeriod').removeAttr('disabled');
}
function EnableControlTemplate() {
    $('#Template').removeAttr('disabled');
}

function DisableControlTemplate() {
    $('#Template').attr('disabled', 'disabled');
}

function DisableHeaderAndDetailAsNeeded() {
    var enableHeaderFields = $('#SecEnableHeaderFields').val();
    var enableDetailGrid = $('#SecEnableDetailGrid').val();
    var enablePostingDateField = $('#SecEnablePostingDateField').val();
    var enablePeriodDropDown = $('#SecEnablePeriodDropDown').val();
    var EnableReversalPeriodDropDown = $('#SecEnableReversalPeriodDropDown').val();
    var enableTemplateDropDown = $('#SecEnableTemplateDropDown').val();
    var enableNameField = $("#SecEnableNameField").val();

    var isAuditView = $('#SecIsAuditView').val();
    if (enableHeaderFields == "False") {
        DisableHeader()
    }
    if (enableDetailGrid == "False") {
        DisableGrid();
    }
    if (enablePostingDateField == "True") {
        EnableControlPostingDate();
    }
    if (enablePeriodDropDown == "True") {
        EnableControlPeriod();
    }
    else {
        DisableControlPeriod();
    }

    if (EnableReversalPeriodDropDown == "True") {
        EnableControlReversalPeriod();
    }
    if (enableTemplateDropDown == "True") {
        EnableControlTemplate();
    }
    else {
        DisableControlTemplate();
    }
    if (isAuditView == "True") {
        HideAllMenuButtons();
    }

    if (enableNameField == "False") {
        DisableNameField();
    }
}

function gridResized(event, ui, fieldSelector) {

    var headerWidth = $(ui.originalElement).width();
    var inputWidth = $(fieldSelector).width();

    //Don't let the width of input fields be smaller than the size of the header & td.
    if (inputWidth < (headerWidth - 4)) {
        $(fieldSelector).width(headerWidth - 4);
    }

    updateGridWidthPrefs();
}

function initGridInputWidth() {
    var headers = $('.ResizeGridHeader');
    var updateInDb = false;
    headers.each(function (i, e) {
        var eachHeader = $(e);
        var classList = eachHeader.attr('class').split(' ');
        $.each(classList, function (ix, eachClassName) {
            if (eachClassName.indexOf('JEPrepCol') != -1) {
                //Do work here.  Must account for input borders (2px each side)
                var headerWidth = eachHeader.width();
                var inputWidth = $('input.' + eachClassName).width();
                if (inputWidth < (headerWidth - 4)) {
                    $('input.' + eachClassName).width(headerWidth - 4);
                    updateInDb = true;
                }
            }
        })
    })
    if (updateInDb) {
        updateGridWidthPrefs();
    }
};

function updateGridWidthPrefs() {
    var headers = $('.ResizeGridHeader');
    var packetString = '';
    headers.each(function (i, element) {
        var widthString = $(element).width();
        var elementId = $(element).attr('id');
        packetString = packetString + elementId + ':' + widthString + ';';
    });

    var templateId = $('#Template_Id').val();
    var packet = { templateId: templateId, columnWidth: packetString };
    $.ajax({
        type: "post",
        url: UpdatePrefURL(),
        data: packet,
        error: DisplayTrintechAjaxError,
        cache: false,
        showBusyCursor: false
    });
}

/**** Scheduled Reversal ====================================================================================****/

function RefreshReversalPeriodList() {
    var reversalPeriod = document.getElementById('ReversalPeriod');
    if (reversalPeriod != null) {
        var selectedJEPeriodId = $("#Period").val();
        if (selectedJEPeriodId === undefined) {
            return;
        }
        var packet = { selectedJEPeriodId: selectedJEPeriodId };
        $.ajax({
            type: "get",
            data: packet,
            datatype: 'json',
            url: GetReversalPeriodListURL(),
            success: RefreshReversalPeriodListSuccess,
            error: DisplayTrintechAjaxError,
            cache: false,
            async: true
        });
    }
}
function RefreshReversalPeriodListSuccess(packet) {
    $("#ReversalPeriod").html('');
    var markup = '';
    for (var x = 0; x < packet.length; x++) {
        markup += '<option value="' + packet[x].Value + '">' + packet[x].Text + '</option>';
    }
    $("#ReversalPeriod").html(markup);
}

function JEPrepReprocessReversalButtonClicked() {
    JEActionWithWholeForm("reprocessreversal");
    DisableReprocessReversalButton();
}

function setReversalPeriod() {
    var selectedReversalPeriod = $('#JERevPerId').val();
    if (selectedReversalPeriod != null && selectedReversalPeriod.length > 0) {
        if ($('#ReversalPeriod') != null) {
            $('#ReversalPeriod').val(selectedReversalPeriod);
        }
    }
}

function SetErrClassForReversalPeriod(errorDictionary) {
    var found = false;
    var cntrlReversalPeriod = 'ReversalPeriod';
    var reversalPeriod = document.getElementById('ReversalPeriod');
    if (reversalPeriod != null) {
        $.each(errorDictionary, function (idx, elem) {
            if (idx == cntrlReversalPeriod) {
                found = true;
                return false;
            }
        });
        if (found == true) {
            $('#ReversalPeriod').addClass('input-validation-error');
        }
        else {
            $('#ReversalPeriod').removeClass('input-validation-error');
        }
    }
}

function ResetValidationForReversalPeriod() {
    var reversalPeriod = $('#ReversalPeriod');
    if (reversalPeriod != null) {
        reversalPeriod.removeClass('input-validation-error');
    }
}


function setRiskRating() {

    var isPosted = document.getElementById('IsPostedView').value.toLowerCase() === 'true';
    var isRiskRatingEnabled = document.getElementById('risk-rating-enabled').value.toLowerCase() === 'true';
    var riskRating = document.getElementById('risk-rating').value;
    var riskRatingInProgress = document.getElementById('risk-rating-in-progress-id').value;
    var riskLevel = document.getElementById('risk-level').value;
    var gaugeElement = document.getElementById('gauge-column');
    var riskRatingError = document.getElementById('risk-rating-error').value.toLowerCase() === 'true';
    var jePrepContainer = document.getElementById('JeTitleAndPrep');

    if (!isRiskRatingEnabled && !(isPosted && riskRating))
        return;

    jePrepContainer.style.minHeight = '10rem';

    gauge = new Gauge({
        notApplicable: GetNotApplicableRiskRatingText(),
        low: GetLowRiskRatingText(),
        medium: GetMediumRiskRatingText(),
        high: GetHighRiskRatingText(),
        error: GetRiskRatingErrorText(),
        toolTip: GetRiskRatingToolTipText(),
        loading: GetRiskRatingLoadingText(),
    });

    gaugeElement.style.display = 'block';

    if (riskRatingInProgress) {
        var url = GetRiskRatingUrl();
        var instance = setInterval(function () {
            $.ajax({
                type: "get",
                url: url,
                success: function (data) { handleRiskRatingResponse(data, instance); },
                error: DisplayTrintechAjaxError,
                cache: false,
                data: { id: riskRatingInProgress }
            });
        }, 1000);
    }
    else if (riskRatingError) {
        gauge.setError();
    }
    else if (riskRating) {
        setRiskRatingAndLevel(riskRating, riskLevel);
    }
 
}


function handleRiskRatingResponse(data, instance) {
    if (data.Error) {
        gauge.setError();
        clearInterval(instance);
        showRiskRatingError(data.Message);
    }

    else if (data.Finished) {
        setRiskRatingAndLevel(data.Rating, data.Level);
        clearInterval(instance);
        $('#riskRatingErrorRow').hide();
    }
}

function showRiskRatingError(message) {
    $('#riskRatingErrorRow').show();
    $('#riskRatingErrorText').text(message);
}

function setRiskRatingAndLevel(riskRating, riskLevel) {

    gauge.setRiskRating(riskRating);


    switch (riskLevel) {
        case 'N':
            gauge.setRiskLevel('not-applicable');
            break;
        case 'L':
            gauge.setRiskLevel('low');
            break;
        case 'M':
            gauge.setRiskLevel('medium');
            break;
        case 'H':
            gauge.setRiskLevel('high');
            break;
    }
}


/**** Scheduled Reversal ====================================================================================****/

/**** Unlocak Posting ====================================================================================****/
function JEPrepUnlockJEForPostingButtonClicked() {
    JEActionWithWholeForm("unlockJEForPosting");
    DisableUnlockJEForPostingButton();
}
/**** Unlocak Posting ====================================================================================****/